layui.use('layim', function (layim) {
    var $ = layui.jquery;
    var userCode = $("#userCode").val();
    var socket = null;  // 判断当前浏览器是否支持WebSocket
    var readOffLineMessage = false;
    if ('WebSocket' in window) {
        var k_host = window.location.host;
        var k_port = window.location.port;
        var wsPath = "ws://" + k_host + k_port + basePath + "/sysMessage/" + userCode;
        socket = new WebSocket(wsPath);
    } else {
        alert('该浏览器不支持本系统即时通讯功能，推荐使用谷歌或火狐浏览器！');
    }
    var autoReplay = [
        '您好，我现在有事不在，一会儿再和您联系。'
    ];
    layim.config({
        init: {
            url: basePath + '/sysUser/findUserInfo'
            , data: {}
        }
        , brief: false
        //查看群员接口
        /*,members: {
           url: 'group/getMemberByGroupId'
          ,data: {}
        }*/
        , uploadImage: {
            url: basePath + '/file/uploadFile'
            , type: '' //默认post
        }
        , uploadFile: {
            url: basePath + '/file/uploadFile'
            , type: '' //默认post
        }
        , min: true
        , title: 'Swyc-layim'        //主面板最小化后显示的名称
        // ,msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
        //,find: layui.cache.dir + 'css/modules/layim/html/find.html' //发现页面地址，若不开启，剔除该项即可
        ,chatLog: basePath+'/sysUser/chatLog?userCode='+userCode //聊天记录页面地址，若不开启，剔除该项即可
        , copyright: true          //是否授权
        , isgroup: false
        //, right: '0px'
        , notice: true      //开启桌面消息提醒
    });

    // 连接发生错误的回调方法
    socket.onerror = function () {
        console.log("连接失败!");
    };
    // 连接成功建立的回调方法
    socket.onopen = function (event) {
        console.log("连接成功!");
    }

    // 接收到消息的回调方法
    socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        console.log(data)
        if ((data.messageType) == "chatMessage") {
            layim.getMessage(data);
            saveToCache(data)
        } else if (data.messageType == "onlineMessage") {
            layim.setFriendStatus(data.userCode, data.status)
        }
    }

    // 连接关闭的回调方法
    socket.onclose = function () {
        console.log(userCode, "退出连接");
    }
    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        socket.close();
    }

    // 监听发送消息
    layim.on('sendMessage', function (data) {
        console.log(data)
        if (data.mine.id == data.to.id) {
            layim.getMessage({
                system: true,
                type: data.to.type,
                content: "不能给自己发送信息",
                id:data.mine.id
            });
        } else {
            var obj = {
                "mine": {
                    "avatar": data.mine.avatar,
                    "content": data.mine.content,
                    "id": data.mine.id,
                    "mine": false,
                    "username": data.mine.username
                },
                "to": {
                    "avatar": data.to.avatar,
                    "id": data.to.id,
                    "name": data.to.groupname,
                    "sign": data.to.sign,
                    "type": data.to.type,
                    "username": data.to.username
                },
                chatType: data.to.chatType || 4
            }
            socket.send(JSON.stringify(obj));  	//发送消息倒Socket服务
        }
    });

    //监听在线状态的切换事件
    layim.on('online', function (data) {
        console.log(data);
    });

    /**
     * 不存缓存  消息显示不正常
     * 我也没法
     * @param message
     */
    function saveToCache(message,saveFirst) {
        var cache =  layui.layim.cache();
        var local = layui.data('layim')[cache.mine.id];
        if(!local){
            local = {}
        }
        if(!local.chatlog){
            var code = message.type+message.id;
            local.chatlog = {};
            local.chatlog[code] = [];

        }
        var messages = local.chatlog[message.type+message.id];
        if(messages&&(saveFirst||messages.length>1)){
            local.chatlog[message.type+message.id].push(message);
            console.log("同步到cache -> ",message.content)
            layui.data('layim', {
                key: cache.mine.id
                ,value: local
            })
        }
    }
    
    function getHistory(code) {
        $.post(basePath+"/message/getHistory",{
            userCode:userCode,
            fromCode:code
        },function (res) {
            if(res.success){
                var data = res.data;
                for(var i = data.length - 1;i >=0;i--){
                    var message = data[i];
                    saveToCache(message);
                }
            }
        })

    }

    function deleteCacheByTypeCode(type,code){
        var cache =  layui.layim.cache();
        var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
        local.chatlog[type+code] = [];
        layui.data('layim', {
            key: cache.mine.id
            ,value: local
        });
    }

    function deleteCache(){
        var cache =  layui.layim.cache();
        var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
        //这里以删除本地聊天记录为例
        if (local && local.chatlog){
            delete local.chatlog;
            //向localStorage同步数据
            layui.data('layim', {
                key: cache.mine.id
                ,value: local
            });
        }
    }
    //layim建立就绪
    layim.on('ready', function () {
        // deleteCache();
        //获取离线消息
        $.post("/sysUser/getOfflineMessages", function (res) {
            if (res.success) {
                if(res.data.length>0){
                    deleteCache()
                }
                $.each(res.data, function (k, v) {
                    saveToCache(v,true);
                    readOffLineMessage = true;
                    layim.getMessage(v);
                });
            }
        });
    });

    //监听查看群员
    layim.on('members', function (data) {
        console.log(data);
    });

    //监听聊天窗口的切换
    layim.on('chatChange', function (event) {
        console.log(event.data)
        if (readOffLineMessage) {
            var data = event.data;
            var url = basePath + "/public/readMessage";
            $.post(url, {
                mineCode:layui.layim.cache().mine.id,
                userCode: data.id
            }, function (res) {
                if (res.success && res.data) {
                    readOffLineMessage = false;
                }
            })
        }
    });

    layim.on('sign', function (value) {
        //console.log(value.length); //获得新的签名
        if (value.length < 200) {
            $.post("sysUser/updateUserInfo", {"code": userCode, "remark": value}, function (result) {
                console.log(result);
            })
        } else {
            layer.msg("签名不能超过200字符！")
        }
    });

});




